package com.test.springsecurity.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.test.springsecurity.util.ResponseResult;
import com.test.springsecurity.util.ResultStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;
import org.springframework.web.bind.annotation.ControllerAdvice;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 全局异常处理解析器，指定用户在无权限时的处理方式
 *
 */

@ControllerAdvice //异常处理注解
public class MyExceptionHandler implements AccessDeniedHandler {


    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, AccessDeniedException accessDeniedException) throws IOException, ServletException {
        //返回结果
        //设置响应头告诉浏览器返回的是JSON格式数据
        response.setContentType("application/json;charset=utf-8");

        ResponseResult<Object> responseResult = new ResponseResult<>();

        responseResult.setCode(403);
        responseResult.setResultStatus(ResultStatus.NO_PERMS);
        responseResult.setMessage("你没有权限");

        //将数据转化成json格式
        String s = new ObjectMapper().writeValueAsString(responseResult);

        //写出数据
        response.getWriter().write(s);

    }
}
